import { BaseComponent } from "components/common/base-component";
import React = require("react");
import { component } from "components/common/component";
import { subscribe } from "common";
import { ShoppingCartService } from "mobile/services/shoppingCartService";
import { MemberService } from "mobile/services/memberService";
import { ShoppingService } from "mobile/services/shoppingService";
import { buttonOnClick } from "maishu-ui-toolkit";

export interface Props {

}

export interface State {
    productsCount?: number,
    items: ShoppingCartItem[],
}

@component()
export class ShoppingCartBar extends BaseComponent<Props, State>{
    member: MemberService;
    shop: ShoppingService;

    constructor(props) {
        super(props);

        this.state = { items: [] };

        this.member = this.createService(MemberService);
        this.shop = this.createService(ShoppingService);
    }

    async buy() {
        let items = this.state.items.filter(o => o.Selected);
        if (items.length <= 0)
            return;

        var productIds = items.map(o => o.ProductId);
        var quantities = items.map(o => o.Count);
        let userInfo = await this.member.userInfo();
        let memberName = userInfo.Mobile || '';
        let order = await this.shop.createOrder(memberName, productIds, quantities);
        this.app.redirect("shopping/orderProducts", { id: order.Id });

        return order;
    }

    componentDidMount() {
        subscribe(this, ShoppingCartService.productsCount, (value) => {
            this.setState({ productsCount: value });
        })
        subscribe(this, ShoppingCartService.items, (value) => {
            console.assert(value != null);
            this.setState({ items: value });
        })
    }

    render() {
        let { productsCount, items } = this.state;

        let totalAmount = 0;
        let selectedCount = 0;
        items.forEach(o => {
            totalAmount = totalAmount + o.Amount * o.Count;
            selectedCount = selectedCount + o.Count;
        });

        return (
            <div className="settlement">
                <div className="pull-left"
                    onClick={() => this.app.forward("shopping/shoppingCart")}>
                    <i className="icon-shopping-cart"></i>
                    {productsCount ? <span className="badge bg-primary">{productsCount}</span> : null}
                </div>
                <div className="pull-right">
                    <label>总计：<span className="price">￥{totalAmount.toFixed(2)}</span></label>
                    <button className="btn btn-primary" disabled={items.length == 0}
                        ref={e => e ? buttonOnClick(e, () => this.buy()) : null}>
                        结算</button></div>
            </div>
        );
    }
}